package com.jwd.avmanager.util;


import com.jwd.avmanager.server.SignalServerHandler;
import io.netty.util.concurrent.DefaultThreadFactory;


import java.util.concurrent.*;

/**
 * @Description:
 * @Author: david
 * @CreateTime: 2022/5/12
 * @Company: jwd
 */
public class ThreadPoolUtil {
    private ExecutorService pool;
    private int coreNum = Runtime.getRuntime().availableProcessors() * 2;
    private int maxPoolNum = coreNum * 2;
    private ArrayBlockingQueue<Runnable> taskQueue;
    private String taskName = "ThreadPoolUtil";

    public ThreadPoolUtil(int coreNum, int maxPoolNum, String taskName) {
        this.taskName = taskName;
        this.coreNum = coreNum;
        this.maxPoolNum = maxPoolNum;
        init();
    }

    public ThreadPoolUtil() {
        init();
    }

    public void init() {
        taskQueue = new ArrayBlockingQueue<Runnable>(20000);
        pool = new ThreadPoolExecutor(coreNum, maxPoolNum, 5, TimeUnit.SECONDS, taskQueue, new DefaultThreadFactory(taskName), new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                DebugLogger.info(taskName + "任务被拒绝"+taskQueue.size());
                if (r instanceof SignalServerHandler.ParseTask){
                    String content = ((SignalServerHandler.ParseTask) r).getPacket().toString();
                    DebugLogger.info("丢弃的内容："+content);
                }
            }
        });
    }
    public ArrayBlockingQueue<Runnable> getTaskQueue() {
        return taskQueue;
    }

    public void execute(Runnable task) {
        pool.execute(task);
    }
}
